# -*- coding: utf-8 -*-
import datetime

import psutil
import win32api

import time
import pywinauto
import pywinauto.clipboard
import pywinauto.application

from . import helper
from .. import config


g_main_window = None


def refresh():
    pywinauto.mouse.click(coords=config.pos_refresh)
    time.sleep(0.5)


def get_order():
    """
    获取未成交的委托
    """
    main_window = helper.active_window()
    pywinauto.mouse.click(coords=config.pos_pt)
    
    columns = ['委托时间', '证券代码', '证券名称', '买卖', '委托状态', '委托数量', '成交数量', '委托价格', '成交价格', '已撤数量', '合同编号', '交易市场', '股东代码']
    
    main_window.type_keys('{F3}')
    # time.sleep(0.2)
    # refresh()
    
    helper.copy_to_clipboard()

    data = pywinauto.clipboard.GetData()
    end_pos = data.find('\n')
    columns = data[:end_pos].split()

    order_list = []
    for i, row_str in enumerate(data.split('\n')):
        if i == 0:
            continue
        row = row_str.split('\t')
        order_list.append({
            'trade_time': row[columns.index('委托时间')],
            'code': row[columns.index('证券代码')],
            'direct': row[columns.index('买卖')],
            'count': int(row[columns.index('委托数量')]),
            'count_ed': int(row[columns.index('成交数量')]),
            'price': float(row[columns.index('委托价格')]),
            'price_ed': float(row[columns.index('成交价格')]),
            'count_withdraw': int(row[columns.index('已撤数量')]),
        })
    return order_list


def get_asset():
    """
    获取资金明细
    """
    helper.active_window()
    pywinauto.mouse.click(coords=config.pos_pt)

    columns = ['资金帐户', '银行名称', '币种', '资金余额', '可用资金', '可取资金', '交易冻结', '委托买入冻结金额', '证券市值', '多金融产品市值', '现金资产', '总资产', '预计利息', '利息税']
    columns = ['资金帐户', '银行名称', '币种', '资金余额', '可用资金', '可取资金', '交易冻结', '委托买入冻结金额', '证券市值', '多金融产品市值', '现金资产', '总资产', '预计利息', '利息税']
    pywinauto.mouse.click(coords=config.pos_asset)
    # pywinauto.mouse.release(coords=config.pos_asset)
    # time.sleep(0.2)
    # refresh()
    
    helper.copy_to_clipboard()

    data = pywinauto.clipboard.GetData()
    data = pywinauto.clipboard.GetData()
    end_pos = data.find('\n')
    columns = data[:end_pos].split()
    # val_1st_row = data[end_pos + 1: end_pos + 1 + data[end_pos + 1:].find('\n')].split()

    detail_list = []
    for i, row_str in enumerate(data.split('\n')):
        if i == 0:
            continue
        row = row_str.split('\t')
        return {'total_money': float(row[columns.index('总资产')]), 'avail_money': float(row[columns.index('可用资金')])}


def get_positions():
    """
    获取持仓
    :return:
    """
    helper.active_window()
    pywinauto.mouse.click(coords=config.pos_pt)
    
    columns = ['证券代码', '证券名称', '股份余额', '实际数量', '可用股份', '冻结数量', '成本价1', '当前价', '浮动盈亏', '盈亏比例(%)', '最新市值', '交易市场']
    columns = ['证券代码', '证券名称', '股份余额', '实际数量', '可用股份', '冻结数量', '成本价1', '当前价', '浮动盈亏', '盈亏比例(%)', '当日盈亏', '当日盈亏比(%)', '最新市值', '仓位占比(%)', '交易市场']
    pywinauto.mouse.click(coords=config.pos_position)
    # pywinauto.mouse.release(coords=config.pos_asset)
    # time.sleep(0.2)
    # refresh()
    
    helper.copy_to_clipboard()

    position_list = []
    data = pywinauto.clipboard.GetData()
    end_pos = data.find('\n')
    columns = data[:end_pos].split()
    # val_1st_row = data[end_pos + 1: end_pos + 1 + data[end_pos + 1:].find('\n')].split()

    detail_list = []
    for i, row_str in enumerate(data.split('\n')):
        if i == 0:
            continue
        row = row_str.split('\t')
        current_position = int(float(row[columns.index('股份余额')]))
        avail_position = int(float(row[columns.index('可用股份')]))
        price = float(row[columns.index('当前价')])
        price_cost = float(row[columns.index('成本价1')])
        profit_total = float(row[columns.index('浮动盈亏')])

        # position = n.Position(row[0], current_position, avail_position)
        position = {
            'code': row[0],
            'current_position': current_position,
            'avail_position': avail_position,
            'price': price,
            'price_cost': price_cost,
            'profit_total': profit_total
        }

        position_list.append(position)

    return position_list


def query_position(code):
    """
    可以卖的股数
    还可以买的股数
    """
    helper.active_window()
    pywinauto.mouse.click(coords=config.pos_pt)
    
    position_list = get_positions()
    if not code:
        return position_list
        
    for position in position_list:
        if position['code'] != code:
            continue
        return [position]


def get_operation_detail(code_in=None):
    """
    获取对账单
    """
    helper.active_window()
    pywinauto.mouse.click(coords=config.pos_pt)
    
    columns = ['成交时间', '发生日期', '证券代码', '证券名称', '业务名称', '发生金额', '资金本次余额', '股份余额', '成交数量', '成交价格', '成交金额', '手续费', '印花税', '附加费', '委托编号', '股东代码', '币种', '过户费', '交易所清算费', '资金帐号', '备注', '费用备注']
    columns = ['发生日期', '成交时间', '证券代码', '证券名称', '业务名称', '成交数量', '成交价格', '成交金额', '余额', '清算金额', '手续费', '印花税', '附加费', '资金本次余额', '委托编号', '股东代码', '过户费', '交易所清算费', '资金帐号', '币种', '费用备注']
    pywinauto.mouse.click(coords=config.pos_detail2)
    # pywinauto.mouse.release(coords=config.pos_detail)
    # time.sleep(0.2)
    # refresh()
    
    helper.copy_to_clipboard()

    data = pywinauto.clipboard.GetData()
    end_pos = data.find('\n')
    columns = data[:end_pos].split()
    # val_1st_row = data[end_pos + 1: end_pos + 1 + data[end_pos + 1:].find('\n')].split()

    detail_list = []
    for i, row_str in enumerate(data.split('\n')):
        if i == 0:
            continue
        row = row_str.split('\t')
        code = row[columns.index('证券代码')]
        if not code:
            continue

        if code_in and code_in != code:
            continue
        trade_time = row[columns.index('成交时间')]
        trade_date = row[columns.index('发生日期')]
        trade_time = datetime.datetime.strptime('{} {}'.format(trade_date, trade_time), '%Y%m%d %H:%M:%S')
        price = float(row[columns.index('成交价格')])
        count = int(float(row[columns.index('成交数量')]))

        detail = {
            'trade_time': trade_time.strftime('%Y-%m-%d %H:%M:%S'),
            'code': code,
            'price': price,
            'count': count
        }

        detail_list.append(detail)
    for row in data.split('\n'):
        val_list = row.split('\t')

    return detail_list


def order(direct, code, count, price=0, auto=False):
    main_window = helper.active_window()
    pywinauto.mouse.click(coords=config.pos_pt)

    # pywinauto.mouse.click(coords=config.pos_asset)
    # time.sleep(0.2)

    if direct == 'B':
        main_window.type_keys('{F2}')
        main_window.type_keys('{F1}')
    else:
        main_window.type_keys('{F1}')
        main_window.type_keys('{F2}')

    main_window.type_keys(str(code))
    main_window.type_keys('{TAB}')
    if price > 0:
        main_window.type_keys(str(price))
    main_window.type_keys('{TAB}')
    main_window.type_keys(str(count))

    if auto:
        main_window.type_keys('{TAB}')
        main_window.type_keys('{ENTER}')
        # time.sleep(0.5)
        # pywinauto.keyboard.send_keys('{ENTER}')
        # time.sleep(0.5)
        # pywinauto.keyboard.send_keys('{ENTER}')


def withdraw(direct):
    pos = ()
    command = ''
    if direct == 'full':
        command = 'z'
        pos = config.pos_withdraw_all
    elif direct == 'buy':
        command = 'x'
        pos = config.pos_withdraw_buy
    elif direct == 'sell':
        command = 'c'
        pos = config.pos_withdraw_sell
    elif direct == 'last':
        command = 'g'
        pos = config.pos_withdraw_last
    else:
        print(direct, ' is unknown')
        return
        
    print('direct is - {}, command is - {}'.format(direct, command))
    
    main_window = helper.active_window()
    pywinauto.mouse.click(coords=config.pos_pt)

    main_window.type_keys('{F3}')

    time.sleep(0.2)
    pywinauto.mouse.click(coords=pos)

    # main_window.type_keys(command)
    # pywinauto.keyboard.send_keys(command)

    time.sleep(0.5)
    pywinauto.keyboard.send_keys('{ENTER}')
